import { type ChangeEvent, type MouseEvent, useContext, useState } from 'react';
import { PostIdH5PageContext } from '@/contexts/mobile/PostId';
import { useMutation } from '@tanstack/react-query';
import type { TBody } from '@/types';
import { createParentReply } from '@/services/api';
import useUser from '@/hooks/useUser';
import useModal from '@/hooks/useModal';
import type { ICreateParentReplyBody } from '@/interfaces';
import sanitizeHtml from 'sanitize-html';
import useToast, { LoginReminderContent } from 'hooks/useToast';
import { useRouter } from 'next/navigation';

export default function ParentReplyBtnPostIdH5Page({
  id,
  alias,
}: {
  id: number;
  alias: string;
}) {
  const context = useContext(PostIdH5PageContext);
  const metadata = context.metadata!;
  const { showModal, hideModal } = useModal();

  function onClickReply() {
    const modal = showModal({
      title: `@${alias}`,
      content: (
        <PostIdH5PageContext.Provider value={{ metadata }}>
          <ReplyModal
            id={id}
            callback={() => {
              hideModal(modal);
            }}
          />
        </PostIdH5PageContext.Provider>
      ),
      isShowFooter: false,
    });
  }

  return (
    <div onClick={onClickReply} className="flex-shrink-0 py-2">
      <i className="bi bi-reply" title="回复"></i>
    </div>
  );
}

const ReplyModal = ({
  id,
  callback,
}: {
  id: number;
  callback?: () => void;
}) => {
  const context = useContext(PostIdH5PageContext);
  const metadata = context.metadata!;
  const userQuery = useUser(metadata);
  const [replyContent, setReplyContent] = useState('');
  const { show } = useToast();
  const router = useRouter();

  const createReplyMutation = useMutation(
    async (variables: TBody<ICreateParentReplyBody>) => {
      await createParentReply(variables);
    },
  );

  async function onClickPostReply(e: MouseEvent<HTMLButtonElement>) {
    try {
      e.stopPropagation();
      e.preventDefault();

      if (!userQuery.data?.user) {
        show({
          type: 'PRIMARY',
          title: '还未登录，是否进行登录?',
          content: <LoginReminderContent />,
        });
        return;
      }

      if (!replyContent.trim()) {
        setReplyContent('');
        show({
          type: 'DANGER',
          message: '回复内容不能为空',
        });
        return;
      }

      const content = sanitizeHtml(replyContent);
      if (!content) {
        setReplyContent('');
        show({
          type: 'DANGER',
          message: '回复内容不能为空',
        });
        return;
      }

      await createReplyMutation.mutateAsync({
        data: {
          replyId: id,
          content,
        },
      });

      setReplyContent('');
      show({
        type: 'SUCCESS',
        message: '回复完成',
      });

      if (callback) {
        callback();
      }

      router.refresh();
    } catch (e) {
      createReplyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeCommentContent(e: ChangeEvent<HTMLTextAreaElement>) {
    setReplyContent(e.target.value);
  }

  return (
    <div className="row">
      <div className="col">
        <form className="vstack gap-4">
          <textarea
            name="replyContent"
            className="form-control"
            rows={5}
            placeholder="请输入回复"
            value={replyContent}
            onChange={onChangeCommentContent}
          ></textarea>
          <button
            onClick={onClickPostReply}
            disabled={createReplyMutation.isLoading || !replyContent}
            type="button"
            className="btn btn-outline-primary"
          >
            {createReplyMutation.isLoading ? (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            ) : (
              <i className="bi bi-cursor me-2"></i>
            )}
            发表回复
          </button>
        </form>
      </div>
    </div>
  );
};
